package com.test45_JUC;

import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;

/**
 * CyclicBarrier：循环栅栏
 * 实现屏障同步等待的处理机制
 */
public class Demo13_CyclicBarrier {

    public static void main(String[] args) throws Exception {
        // test1();
        // test2();
        test3();
    }

    public static void test1() throws Exception {
        CyclicBarrier barrier = new CyclicBarrier(2);   // 设置栅栏的数量为2
        for (int x = 0; x < 4; x++) {
            new Thread(() -> {
                try {
                    System.out.printf("【Barrier - 等待开始】当前的线程名称：%s%n", Thread.currentThread().getName());
                    barrier.await();    // 等待，凑够了2个等待的线程
                    TimeUnit.SECONDS.sleep(1);
                    System.err.printf("【Barrier - 处理完毕】当前的线程名称：%s%n", Thread.currentThread().getName());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }, "执行者-" + x).start();
            TimeUnit.SECONDS.sleep(1);
        }
    }

    public static void test2() throws Exception {
        CyclicBarrier barrier = new CyclicBarrier(2);   // 设置栅栏的数量为2
        for (int x = 0; x < 3; x++) {
            final int temp = x;
            new Thread(() -> {
                try {
                    System.out.printf("【Barrier - 等待开始】当前的线程名称：%s%n", Thread.currentThread().getName());
                    TimeUnit.SECONDS.sleep(1);
                    if (temp == 2) {
                        barrier.reset();    // 重置
                    } else {
                        barrier.await();    // 等待，凑够了2个等待的线程
                    }
                    System.err.printf("【Barrier - 处理完毕】当前的线程名称：%s%n", Thread.currentThread().getName());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }, "执行者-" + x).start();
            TimeUnit.SECONDS.sleep(1);
        }
    }

    /**
     * 设置达到屏障后的处理线程
     */
    public static void test3() throws Exception {
        CyclicBarrier barrier = new CyclicBarrier(2, () -> {
            System.out.println("【屏障业务处理】两个子线程已就绪，可以开始执行屏障线程控制。");
        });
        for (int x = 0; x < 4; x++) {
            new Thread(() -> {
                try {
                    System.out.printf("【Barrier - 等待开始】当前的线程名称：%s%n", Thread.currentThread().getName());
                    TimeUnit.SECONDS.sleep(1);
                    barrier.await();    // 等待，凑够了2个等待的线程
                    System.err.printf("【Barrier - 处理完毕】当前的线程名称：%s%n", Thread.currentThread().getName());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }, "执行者-" + x).start();
            TimeUnit.SECONDS.sleep(1);
        }
    }
}
